//
//  VC6Layer.swift
//  ChapterAll
//
//  Created by Kevin on 2020/4/27.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

class VC6Layer: UIViewController {
    
    lazy var redView = {()->UIView in
        let w:CGFloat = 100
        let h:CGFloat = 100
        let x = (view.frame.width - w) * 0.5
        let ui = UIView()
        ui.backgroundColor = UIColor.red
        ui.frame = CGRect(x: x, y: 200, width: w, height: h)
        return ui
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(redView)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        test10()
    }
    
    func test10() -> Void {
        // 开启图片上下文
        UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0)
        guard let ctx = UIGraphicsGetCurrentContext() else {
            return
        }
        view.layer.render(in: ctx)
        // 获取图片
        guard let img = UIGraphicsGetImageFromCurrentImageContext() else {
            return
        }
        // 关闭图片上下文
        UIGraphicsEndImageContext()
        
        // 保存图片
        let file = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        guard let path = file as NSString? else {
            return
        }
        // 图片保存路径
        let filePath = path.appendingPathComponent("redview.png")
        print("path=\(filePath)")
        // 转成二进制
        guard let data = img.pngData() else {
            return
        }
        try? data.write(to: URL(fileURLWithPath: filePath))
    }
    
    // 2D 原始基础上缩放
    func test9() -> Void {
        redView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
    }
    
    // 3D 原始基础上缩放
    func test8() -> Void {
        redView.transform3D = CATransform3DMakeScale(0.5, 0.5, 0)
    }
    
    // 3D 最终位置上缩放
    func test7() -> Void {
        redView.layer.transform = CATransform3DScale(redView.transform3D, 0.5, 0.5, 0)
    }
    
    // 2D 原始基础上旋转
    func test6() -> Void {
        redView.transform = CGAffineTransform(rotationAngle: 180)
    }
    
    // 3D 原始基础上旋转
    func test5() -> Void {
        redView.layer.transform = CATransform3DMakeRotation(180, 0, 0, 1)
    }
    
    // 3D 最终位置上旋转
    func test4() -> Void {
        redView.layer.transform = CATransform3DRotate(redView.layer.transform, 180, 0, 0, 1)
    }
    
    // 2D 原始基础上平移
    func test3() -> Void {
        redView.transform = CGAffineTransform(translationX: 20, y: 0)
    }
    
    // 3D 最终位置上平移
    func test2() -> Void {
        redView.layer.transform = CATransform3DMakeTranslation(20, 0, 0)
    }
    
    // 3D 原始基础上平移
    func test1() -> Void {
        redView.layer.transform = CATransform3DTranslate(redView.layer.transform, 20, 0, 0)
    }
}
